package com.qsmx.qingqiuticket.app.delegate.group;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qsmx.core.delegates.AtmosDelegate;
import com.qsmx.core.net.HttpHelper;
import com.qsmx.core.net.callback.IError;
import com.qsmx.core.net.callback.IFailure;
import com.qsmx.core.net.callback.ISuccess;
import com.qsmx.core.util.ClickUtil;
import com.qsmx.core.util.CountDownTimerUtil;
import com.qsmx.core.util.StringUtil;
import com.qsmx.core.util.dialog.DialogUtil;
import com.qsmx.core.util.dimen.DimenUtil;
import com.qsmx.core.util.storage.AtmosPreference;
import com.qsmx.core.util.zxing.ZXingUtil;
import com.qsmx.qingqiuticket.app.R;
import com.qsmx.qingqiuticket.app.databinding.DelegateGroupSessionListBinding;
import com.qsmx.qingqiuticket.app.delegate.HomeDelegate;
import com.qsmx.qingqiuticket.app.delegate.HomeLoginMemDelegate;
import com.qsmx.qingqiuticket.app.delegate.adapter.SessionListAdapter;
import com.qsmx.qingqiuticket.app.entity.LockSessionEntity;
import com.qsmx.qingqiuticket.app.entity.SessionListEntity;
import com.qsmx.qingqiuticket.app.fusion.FusionCode;
import com.qsmx.qingqiuticket.app.fusion.FusionData;
import com.qsmx.qingqiuticket.app.fusion.FusionPre;
import com.qsmx.qingqiuticket.app.fusion.FusionTag;
import com.qsmx.qingqiuticket.app.net.HttpUrl;
import com.qsmx.qingqiuticket.app.util.SoundPlayUtils;

import java.lang.reflect.Type;

public class GroupSessionListDelegate extends AtmosDelegate {
    private CountDownTimerUtil timer;
    private DelegateGroupSessionListBinding mBinding;
    private SessionListEntity mData;
    private String orderNo = "";
    private String packageId = "";
    private String packageName = "";
    private String packageNum = "";

    public AppCompatImageView ivQrCode;

    private Dialog mQrDialog;
    private int doorTicket = 0;
    private int onceTicket = 0;
    private SessionListAdapter mAdapter;
    private String mVerifyCode = "";
    private boolean isShowDesc = false;

    private int perGiveIntegral = 0;
    private int perGiveGrowth = 0;

    @Override
    public Object setLayout() {
        return R.layout.delegate_group_session_list;
    }

    public static GroupSessionListDelegate create(String orderNo, String packageId, String packageName, String packageNum, int doorTicket, int onceTicket, String verifyCode, boolean isShowDesc, int perGiveIntegral, int perGiveGrowth) {

        final Bundle args = new Bundle();
        args.putString(FusionTag.ORDER_NO, orderNo);
        args.putString(FusionTag.PACKAGE_ID, packageId);
        args.putString(FusionTag.PACKAGE_NAME, packageName);
        args.putString(FusionTag.PACKAGE_NUM, packageNum);
        args.putInt(FusionTag.DOOR_TICKET, doorTicket);
        args.putInt(FusionTag.ONCE_TICKET, onceTicket);
        args.putString(FusionTag.VERIFY_CODE, verifyCode);
        args.putBoolean(FusionTag.IS_SHOW_DESC, isShowDesc);
        args.putInt(FusionTag.PER_GIVE_INTEGRAL, perGiveIntegral);
        args.putInt(FusionTag.PER_GIVE_GROWTH, perGiveGrowth);

        final GroupSessionListDelegate delegate = new GroupSessionListDelegate();
        delegate.setArguments(args);
        return delegate;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Bundle args = getArguments();
        if (args != null) {
            orderNo = args.getString(FusionTag.ORDER_NO);
            packageId = args.getString(FusionTag.PACKAGE_ID);
            packageName = args.getString(FusionTag.PACKAGE_NAME);
            packageNum = args.getString(FusionTag.PACKAGE_NUM);
            doorTicket = args.getInt(FusionTag.DOOR_TICKET);
            onceTicket = args.getInt(FusionTag.ONCE_TICKET);
            mVerifyCode = args.getString(FusionTag.VERIFY_CODE);
            isShowDesc = args.getBoolean(FusionTag.IS_SHOW_DESC, false);
            perGiveIntegral = args.getInt(FusionTag.PER_GIVE_INTEGRAL, 0);
            perGiveGrowth = args.getInt(FusionTag.PER_GIVE_GROWTH, 0);
        }
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        mBinding = DelegateGroupSessionListBinding.bind(rootView);
        SoundPlayUtils.play(3);

        getSessionList(packageId, doorTicket * StringUtil.IntegerValueOf(packageNum, 1));

        mBinding.tvPackageName.setText(packageName);
        mBinding.tvTicketNum.setText((Html.fromHtml(String.format(getString(R.string.ticket_num_tips), doorTicket * StringUtil.IntegerValueOf(packageNum, 1) + ""))));

        mAdapter = new SessionListAdapter(getContext());
        mBinding.rlvSessionList.setAdapter(mAdapter);
        mBinding.rlvSessionList.setLayoutManager(new LinearLayoutManager(getContext()));

        mBinding.tvRefreshSession.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getSessionList(packageId, doorTicket * StringUtil.IntegerValueOf(packageNum, 1));
            }
        });

        mBinding.tvBackHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtil.isNotFastClick()) {
                    getSupportDelegate().pop();
                }
            }
        });

        mBinding.tvMiniProgramTips.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        mBinding.clLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtil.isNotFastClick()) {
                    getSupportDelegate().start(new HomeLoginMemDelegate());
                }
            }
        });
        mAdapter.setonItemClickListener(new SessionListAdapter.OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                if (ClickUtil.isNotFastClick()) {
                    lockSession(mAdapter.getData().get(position).getSessionId(), packageNum);
                }
            }
        });

    }

    @SuppressLint("SetTextI18n")
    public void showQRDialog() {
        if (mQrDialog != null) {
            mQrDialog.dismiss();
        } else {
            mQrDialog = new Dialog(requireContext(), com.qsmx.core.R.style.dialog);
        }

        mQrDialog.setCancelable(false);
        Window window = mQrDialog.getWindow();
        window.setContentView(R.layout.dialog_show_qrcode);
        int width = (int) (DimenUtil.getScreenWidth() * 0.6);
        window.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT);
        mQrDialog.show();

        AppCompatImageView ivClose = window.findViewById(R.id.iv_close);
        ivQrCode = window.findViewById(R.id.iv_qr_code);

        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mQrDialog.dismiss();
            }
        });

        showQrCodeImageView(AtmosPreference.getCustomStringPre(FusionPre.MINI_CODE));

    }

    private void showQrCodeImageView(String qrCode) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = ZXingUtil.generateQRCode(qrCode);
                getProxyActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            ivQrCode.setImageBitmap(bitmap);
                        } catch (Exception e) {

                        }
                    }
                });
            }
        }).start();

    }


    private void lockSession(String sessionId, String reserveQuantity) {
        DialogUtil.showLoadingDialog(getContext(), "正在锁定场次...");

        JSONObject params = new JSONObject();
        params.put("cashierNo", AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM) + "-" + AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM));
        params.put("packageId", packageId);
        params.put("sessionId", sessionId);
        params.put("reserveQuantity", reserveQuantity);
        if (FusionData.mMemData != null) {
            params.put("memberUuid", FusionData.mMemData.getUserId());
        }
        params.put("orderNo", orderNo);

        HttpHelper.RestClientPostRaw(params, HttpUrl.LOCK_SESSION,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        DialogUtil.dismissLoadingDialog();
                        try {
                            Type type = new TypeToken<LockSessionEntity>() {
                            }.getType();
                            Gson gson = new Gson();
                            LockSessionEntity mData = gson.fromJson(response, type);
                            if (mData.getHeader().getCode().equals(FusionCode.SUCCESS)) {
                                getSupportDelegate().start(GroupOrderDelegate.create(mData.getBody().getOrderNo(),
                                        String.valueOf(doorTicket * StringUtil.IntegerValueOf(packageNum, 1)),
                                        String.valueOf(onceTicket * StringUtil.IntegerValueOf(packageNum, 1)),
                                        mData.getBody().getSessionDate() + " " + mData.getBody().getSessionStartTime() + "-" + mData.getBody().getSessionEndTime(),
                                        mData.getBody().getSessionNo(),
                                        mData.getBody().getGiveIntegral() + "",
                                        mData.getBody().getGiveGrowth() + "",
                                        mVerifyCode, packageNum, perGiveIntegral, perGiveGrowth
                                ));
                            } else {
                                DialogUtil.showCardErrorDialog(getContext(), mData.getHeader().getMessage(), "确定");
                            }
                        } catch (Exception e) {
                            DialogUtil.showCardErrorDialog(getContext(), e.getMessage(), "确定");
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        DialogUtil.dismissLoadingDialog();
                        DialogUtil.showCardErrorDialog(getContext(), msg, "确定");
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {
                        DialogUtil.dismissLoadingDialog();
                        DialogUtil.showCardErrorDialog(getContext(), getString(R.string.un_know_net_error), "确定");
                    }
                });

    }

    private void getSessionList(String packageId, int ticketNum) {
        DialogUtil.showLoadingDialog(getContext(), "正在获取场次信息...");
        JSONObject params = new JSONObject();
        params.put("cashierNo", AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM) + "-" + AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM));
        params.put("packageId", packageId);

        HttpHelper.RestClientPostRaw(params, HttpUrl.GET_SESSION_LIST,
                new ISuccess() {
                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void onSuccess(int code, String response) {
                        DialogUtil.dismissLoadingDialog();
                        try {
                            Type type = new TypeToken<SessionListEntity>() {
                            }.getType();
                            Gson gson = new Gson();
                            mData = gson.fromJson(response, type);
                            if (mData.getHeader().getCode().equals(FusionCode.SUCCESS)) {
                                if (mData.getBody() != null && !mData.getBody().isEmpty()) {
                                    mBinding.clNoSession.setVisibility(View.GONE);
                                    mBinding.clSessionList.setVisibility(View.VISIBLE);
                                    mAdapter.setData(mData.getBody(), ticketNum, isShowDesc);
                                    mAdapter.notifyDataSetChanged();
                                } else {
                                    mBinding.clNoSession.setVisibility(View.VISIBLE);
                                    mBinding.clSessionList.setVisibility(View.GONE);
                                }
                            } else {
                                mBinding.clNoSession.setVisibility(View.VISIBLE);
                                mBinding.clSessionList.setVisibility(View.GONE);
                                DialogUtil.showCardErrorDialog(GroupSessionListDelegate.this, getContext(), mData.getHeader().getMessage(), "确定", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        DialogUtil.dismissErrorDialog();
                                        getSupportDelegate().pop();
                                    }
                                });
                            }
                        } catch (Exception e) {
                            DialogUtil.showCardErrorDialog(GroupSessionListDelegate.this, getContext(), e.getMessage(), "确定", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    DialogUtil.dismissErrorDialog();
                                    getSupportDelegate().pop();
                                }
                            });
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        DialogUtil.dismissLoadingDialog();
                        DialogUtil.showCardErrorDialog(GroupSessionListDelegate.this, getContext(), msg, "确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                DialogUtil.dismissErrorDialog();
                                getSupportDelegate().pop();
                            }
                        });
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {
                        DialogUtil.dismissLoadingDialog();
                        DialogUtil.showCardErrorDialog(GroupSessionListDelegate.this, getContext(), getString(R.string.un_know_net_error), "确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                DialogUtil.dismissErrorDialog();
                                getSupportDelegate().pop();
                            }
                        });
                    }
                });
    }

    private void startCountDownTime(final long time) {
        if (timer != null) {
            timer.cancel();
        }
        timer = new CountDownTimerUtil(time * 1000, 1000) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                mBinding.tvBackHome.setText(String.format(getString(R.string.back_before), String.valueOf(millisUntilFinished / 1000)));
            }

            @Override
            public void onFinish() {
                getSupportDelegate().popTo(HomeDelegate.class, false);
            }
        };
        timer.start();// 开始计时
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        startCountDownTime(60);
        if (FusionData.mMemData != null) {
            mBinding.tvMemInfo.setText(StringUtil.getPhoneNum(FusionData.mMemData.getPhone()));
        }
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    public void onDestroy() {
        if (timer != null) {
            timer.cancel();
        }
        if (mQrDialog != null && mQrDialog.isShowing()) {
            mQrDialog.dismiss();
        }
        super.onDestroy();
    }
}
